package com.git.smp.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.git.smp.cache.DataDictionaryCache;
import com.git.smp.cache.SmpSystemCache;
import com.git.smp.core.ResponseMessage;
import com.git.smp.dao.SmpFieldMapper;
import com.git.smp.dao.SmpServiceHisMapper;
import com.git.smp.dao.SmpServiceMapper;
import com.git.smp.dao.SmpSystemCallMapper;
import com.git.smp.dao.SmpSystemMapper;
import com.git.smp.dao.smpFieldHisMapper;
import com.git.smp.entity.CallListInfo;
import com.git.smp.entity.Menu;
import com.git.smp.entity.SmpField;
import com.git.smp.entity.SmpService;
import com.git.smp.entity.SmpServiceExtend;
import com.git.smp.entity.SmpServiceHis;
import com.git.smp.entity.SmpServiceHisExtend;
import com.git.smp.entity.SmpSystem;
import com.git.smp.entity.SmpSystemCall;
import com.git.smp.entity.smpFieldHis;
import com.git.smp.utils.StringUtil;

import freemarker.core.ParseException;
import freemarker.template.Configuration;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateNotFoundException;



@RequestMapping("/report")
@RestController
public class ExportReportController {
	
	@Autowired
	private Configuration configuration;
	
	@Autowired
	private HttpServletResponse response;
	
	@Autowired
	private SmpServiceMapper serviceMapper;
	
	@Autowired
	private SmpServiceHisMapper serviceHisMapper;

	@Autowired
	private SmpSystemCallMapper callMapper;
	
	@Autowired
	private SmpSystemMapper smpSystemMapper;

	@Autowired
	private SmpFieldMapper smpFiledMapper;
	
	@Autowired
	private smpFieldHisMapper fieldHisMapper;
	
	@RequestMapping("/index")
	public  ResponseMessage<String> index(@RequestParam String qmsName,@RequestParam String qmsNo,@RequestParam String batchNum) throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException, TemplateException {
		ResponseMessage<String> responseMessage = new ResponseMessage<String>();
		responseMessage.setCode("0000");
		responseMessage.setMessage("查询成功！");
		
		Template template = configuration.getTemplate("report.ftl");
		StringWriter writer =new StringWriter();
		Map params = new HashMap<>();
		params.put("qmsNo", qmsNo);
		params.put("qmsName", qmsName);
		params.put("batchNum", batchNum);
		params.put("batchNumStr", DataDictionaryCache.getItemName("SMP0010", batchNum));
		
		
		
		SmpService service= new SmpService();
		service.setQmsNo(qmsNo);
		service.setBatchNum(batchNum);
		List<SmpServiceExtend> services =  serviceMapper.selectreport(service);
		params.put("serversCount", services.size());
		params.put("services", services);
		
		
		List systemAll = new ArrayList<>();
		
		
		List<String> listcreate = new ArrayList<>();
		List<String> listupdate = new ArrayList<>();
		
		List<Map> listupdateDetail = new ArrayList<Map>();
		
		
		for(SmpServiceExtend info:services) {
			if("01".equals(info.getCreateFlg())) {
				listcreate.add(info.getTransCode()+"("+info.getTransName()+")");
			}else {
				listupdate.add(info.getTransCode()+"("+info.getTransName()+")");
				//修改接口字段比较
				SmpServiceHisExtend smpServiceHisExtend = new SmpServiceHisExtend();
				smpServiceHisExtend.setBatchNum(batchNum);
				smpServiceHisExtend.setQmsNo(qmsNo);
				smpServiceHisExtend.setSystemNo(info.getSystemNo());
				smpServiceHisExtend.setTransCode(info.getTransCode());
				SmpServiceHis smpServiceHis =  serviceHisMapper.getHisServiceForReport(smpServiceHisExtend);
				//版本比较
				Map fieldInfo = getFieldBySmpAndHis(smpServiceHis, info);
				
				listupdateDetail.add(fieldInfo);

			}
			systemAll.add(info.getSystemName());
			if(info.getPubSysName()!=null) {
				String[]  names = info.getPubSysName().split(",");
				for(String name: names) {
					systemAll.add(name);
				}
			}
		}
		params.put("serversinfoCreate", String.join("、",listcreate));
		params.put("serversinfoUpdate", String.join("、",listupdate));
		params.put("serversCountCreate", listcreate.size());
		params.put("serversCountUpdate", listupdate.size());
		params.put("listupdateDetail", listupdateDetail);
		params.put("listupdateDetailCount", listupdateDetail.size());
		
		
		
		
		
		
		
		
		
		//调用关系
		SmpSystemCall smpSystemCall = new SmpSystemCall();
		smpSystemCall.setBatchNum(batchNum);
		smpSystemCall.setAssociatedRequirement(qmsNo);
		
		List<CallListInfo>  calllistInfo = callMapper.getConsumeInfoByQmsNo(smpSystemCall);
		params.put("callListCount", calllistInfo.size());
		
		List calllist = new ArrayList<>();
		for(CallListInfo info:calllistInfo) {
			Map map = new HashMap<>();
			map.put("pubSysNo", info.getSystemNo());
			map.put("pubSysName", info.getSystemName());
			map.put("regSysNo", info.getRegSysCode());
			map.put("regSysName", SmpSystemCache.getSystemName(info.getRegSysCode()));
			map.put("transCode", info.getTransCode());
			map.put("transName", info.getTransName());
			calllist.add(map);
			systemAll.add(info.getSystemName()+"("+info.getSystemNo()+")");
			systemAll.add(SmpSystemCache.getSystemName(info.getRegSysCode())+"("+info.getRegSysCode()+")");
		}
		
		params.put("calllist", calllist);
		
		
		//新增系统
		SmpSystem smpSystem = new SmpSystem(); 
		smpSystem.setAssociatedRequirement(qmsNo);
		smpSystem.setBatchNum(batchNum);
		List<SmpSystem> smpSystemList =  smpSystemMapper.getSystemInfoByPage(smpSystem);
		List<String> syslist = new ArrayList<>();
		for(SmpSystem info:smpSystemList) {
			syslist.add(info.getSystemName()+"("+info.getSystemNo()+")");
			systemAll.add(info.getSystemName()+"("+info.getSystemNo()+")");
		}
		params.put("smpSysteminfo", String.join("、",syslist));
		params.put("systemCount", smpSystemList.size());
		
		//涉及系统
		
	    Set<String>  sysall = new HashSet<>(systemAll);
		List<String> sall = new ArrayList<>(sysall);
		
		params.put("systemAll", String.join("、",sall));
		params.put("systemAllCount", sall.size());
		template.process(params, writer);
		
		responseMessage.setExtend(writer.toString());
		writer.close();
		return responseMessage;
	}
	
	@RequestMapping("/doc")
	public  void doc(@RequestParam String qmsName,@RequestParam String qmsNo,@RequestParam String batchNum) throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException, TemplateException {
		OutputStream out = response.getOutputStream();
		Template template = configuration.getTemplate("reportdoc.ftl");
		OutputStreamWriter writer =new OutputStreamWriter(out);
		Map params = new HashMap<>();
		params.put("qmsNo", qmsNo);
		params.put("qmsName", qmsName);
		params.put("batchNum", batchNum);
		params.put("batchNumStr", DataDictionaryCache.getItemName("SMP0010", batchNum));
		
		
		SmpService service= new SmpService();
		service.setQmsNo(qmsNo);
		service.setBatchNum(batchNum);
		List<SmpServiceExtend> services =  serviceMapper.selectreport(service);
		params.put("serversCount", services.size());
		params.put("services", services);
		
		
		List systemAll = new ArrayList<>();
		
		
		List<String> listcreate = new ArrayList<>();
		List<String> listupdate = new ArrayList<>();
		
		List<Map> listupdateDetail = new ArrayList<Map>();
		
		
		for(SmpServiceExtend info:services) {
			if("01".equals(info.getCreateFlg())) {
				listcreate.add(info.getTransCode()+"("+info.getTransName()+")");
			}else {
				listupdate.add(info.getTransCode()+"("+info.getTransName()+")");
				//修改接口字段比较
				SmpServiceHisExtend smpServiceHisExtend = new SmpServiceHisExtend();
				smpServiceHisExtend.setBatchNum(batchNum);
				smpServiceHisExtend.setQmsNo(qmsNo);
				smpServiceHisExtend.setSystemNo(info.getSystemNo());
				smpServiceHisExtend.setTransCode(info.getTransCode());
				SmpServiceHis smpServiceHis =  serviceHisMapper.getHisServiceForReport(smpServiceHisExtend);
				//版本比较
				Map fieldInfo = getFieldBySmpAndHis(smpServiceHis, info);
				
				listupdateDetail.add(fieldInfo);

			}
			systemAll.add(info.getSystemName());
			if(info.getPubSysName()!=null) {
				String[]  names = info.getPubSysName().split(",");
				for(String name: names) {
					systemAll.add(name);
				}
			}
		}
		params.put("serversinfoCreate", String.join("、",listcreate));
		params.put("serversinfoUpdate", String.join("、",listupdate));
		params.put("serversCountCreate", listcreate.size());
		params.put("serversCountUpdate", listupdate.size());
		params.put("listupdateDetail", listupdateDetail);
		params.put("listupdateDetailCount", listupdateDetail.size());
		
		//调用关系
		SmpSystemCall smpSystemCall = new SmpSystemCall();
		smpSystemCall.setBatchNum(batchNum);
		smpSystemCall.setAssociatedRequirement(qmsNo);
		
		List<CallListInfo>  calllistInfo = callMapper.getConsumeInfoByQmsNo(smpSystemCall);
		params.put("callListCount", calllistInfo.size());
		
		List calllist = new ArrayList<>();
		for(CallListInfo info:calllistInfo) {
			Map map = new HashMap<>();
			map.put("pubSysNo", info.getSystemNo());
			map.put("pubSysName", info.getSystemName());
			map.put("regSysNo", info.getRegSysCode());
			map.put("regSysName", SmpSystemCache.getSystemName(info.getRegSysCode()));
			map.put("transCode", info.getTransCode());
			map.put("transName", info.getTransName());
			calllist.add(map);
			systemAll.add(info.getSystemName()+"("+info.getSystemNo()+")");
			systemAll.add(SmpSystemCache.getSystemName(info.getRegSysCode())+"("+info.getRegSysCode()+")");
		}
		
		params.put("calllist", calllist);
		
		
		//新增系统
		SmpSystem smpSystem = new SmpSystem(); 
		smpSystem.setAssociatedRequirement(qmsNo);
		smpSystem.setBatchNum(batchNum);
		List<SmpSystem> smpSystemList =  smpSystemMapper.getSystemInfoByPage(smpSystem);
		List<String> syslist = new ArrayList<>();
		for(SmpSystem info:smpSystemList) {
			syslist.add(info.getSystemName()+"("+info.getSystemNo()+")");
			systemAll.add(info.getSystemName()+"("+info.getSystemNo()+")");
		}
		params.put("smpSysteminfo", String.join("、",syslist));
		params.put("systemCount", smpSystemList.size());
		//涉及系统
		
	    Set<String>  sysall = new HashSet<>(systemAll);
		List<String> sall = new ArrayList<>(sysall);
		
		params.put("systemAll", String.join("、",sall));
		params.put("systemAllCount", sall.size());
		template.process(params, writer);
		writer.close();
	}
	
	/**
	 * 历史版本字段比较
	 * @param id
	 * @return
	 */
	private  Map getFieldBySmpAndHis(SmpServiceHis smpServiceHis,SmpServiceExtend smpService) {
		
		List<String> createField = new ArrayList<>();
		List<String> updateField = new ArrayList<>();
		List<String> deleteField = new ArrayList<>();

		SmpField smpField0  = new SmpField();
		smpField0.setTransCode(smpService.getTransCode());
		smpField0.setSystemNo(smpService.getSystemNo());
		
		List<SmpField> smpFieldList = smpFiledMapper.getFieldByServer(smpField0);
		
		
		smpFieldHis fieldHis = new smpFieldHis();
		fieldHis.setServiceHisId(smpServiceHis.getId());
		List<smpFieldHis> fieldHisList = fieldHisMapper.getHisFieldByServer(fieldHis);
		
		
		for (SmpField smpField : smpFieldList) {
			String versionType = "03"; //新增
			for(smpFieldHis smpFieldHis2: fieldHisList) {
				if(	
						StringUtil.equals(smpField.getFieldCode(),smpFieldHis2.getFieldCode()) &&
					    StringUtil.equals(smpField.getParentType(),smpFieldHis2.getParentType()) &&
					    StringUtil.equals(smpField.getStruct(),smpFieldHis2.getStruct()) &&
					    StringUtil.equals(smpField.getInOut(),smpFieldHis2.getInOut())
				   ) { //字段相等
					
					if(
					/*
					 * StringUtil.equals(smpField.getOrderNumber(),applyField2.getOrderNumber()) &&
					 */		StringUtil.equals(smpField.getFieldName(),smpFieldHis2.getFieldName()) &&
						    StringUtil.equals(smpField.getNodeType(),smpFieldHis2.getNodeType()) &&
						    StringUtil.equals(smpField.getFieldType(),smpFieldHis2.getFieldType()) &&
						    StringUtil.equals(smpField.getFieldLength(),smpFieldHis2.getFieldLength()) &&
						    StringUtil.equals(smpField.getFieldRequire(),smpFieldHis2.getFieldRequire()) &&
						    StringUtil.equals(smpField.getFieldEdsc(),smpFieldHis2.getFieldEdsc())
								) {
							versionType = "01"; //正常
						}else {
							versionType = "02"; //修改
						}
					
					break;
				}
			}
			//smpField.setVersionType(versionType);
			if("03".equals(versionType)) {
				createField.add(smpField.getFieldName()+"("+smpField.getFieldCode()+")");
			}else if("02".equals(versionType)) {
				updateField.add(smpField.getFieldName()+"("+smpField.getFieldCode()+")");
			}
			
		}
		
		for (smpFieldHis smpFieldHis2: fieldHisList) {
			String versionType = "04"; //删除
			for(SmpField smpField : smpFieldList) {
				if(
						StringUtil.equals(smpField.getFieldCode(),smpFieldHis2.getFieldCode()) &&
					    StringUtil.equals(smpField.getParentType(),smpFieldHis2.getParentType()) &&
					    StringUtil.equals(smpField.getStruct(),smpFieldHis2.getStruct()) &&
					    StringUtil.equals(smpField.getInOut(),smpFieldHis2.getInOut())
				   ) { //字段相等
					if(
					/*
					 * StringUtil.equals(smpField.getOrderNumber(),applyField2.getOrderNumber()) &&
					 */		StringUtil.equals(smpField.getFieldName(),smpFieldHis2.getFieldName()) &&
						    StringUtil.equals(smpField.getNodeType(),smpFieldHis2.getNodeType()) &&
						    StringUtil.equals(smpField.getFieldType(),smpFieldHis2.getFieldType()) &&
						    StringUtil.equals(smpField.getFieldLength(),smpFieldHis2.getFieldLength()) &&
						    StringUtil.equals(smpField.getFieldRequire(),smpFieldHis2.getFieldRequire()) &&
						    StringUtil.equals(smpField.getFieldEdsc(),smpFieldHis2.getFieldEdsc())
								) {
							versionType = "01"; //正常
						}else {
							versionType = "02"; //修改
						}
					break;
				}
			}
			//smpFieldHis2.setVersionType(versionType);
			if("04".equals(versionType)) {
				deleteField.add(smpFieldHis2.getFieldName()+"("+smpFieldHis2.getFieldCode()+")");
			}
		}
		
		Map map = new HashMap();
		
		List<String> detail = new ArrayList<>();
		if(updateField.size()>0) {
			detail.add( "新增字段"+ String.join("、",createField));
		}
		if(updateField.size()>0) {
			detail.add("修改字段"+String.join("、",updateField));
		}
		
		if(updateField.size()>0) {
			detail.add( "删除字段"+ String.join("、",deleteField));
		}
		
		if(detail.size()>0) {
			map.put("fieldInfo", String.join(",",detail));
		}else {
			map.put("fieldInfo", "无字段修改");
		}
		
		map.put("service", smpService);
		return map;
	}
	
	
}
